package org.benjamin.lending.service.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.MemberInfo;
import org.benjamin.lending.domain.entity.MemberMoney;
import org.benjamin.lending.domain.entity.MemberMoneyLog;
import org.benjamin.lending.domain.entity.RechargeLog;
import org.benjamin.lending.repository.MemberInfoRepository;
import org.benjamin.lending.repository.MemberMoneyRepository;
import org.benjamin.lending.repository.RechargeLogRepository;
import org.benjamin.lending.service.MemberService;
import org.benjamin.lending.service.RechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;

/**
 * Created by xywen on 2017/5/22.
 */
@Service("rechargeService")
public class RechargeServiceImpl implements RechargeService {

    private final Logger logger = LogManager.getLogger();

    @Autowired
    private RechargeLogRepository rechargeLogRepository;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberInfoRepository memberInfoRepository;

    @Override
    public RechargeLog createRechargeLog(MemberInfo memberInfo,String bank, BigDecimal amount,BigDecimal fee,String createIp) {
        RechargeLog rechargeLog = new RechargeLog();
        rechargeLog.setMemberInfo(memberInfo);
        rechargeLog.setBank(bank);
        rechargeLog.setMoney(amount);
        rechargeLog.setFee(fee);
        rechargeLog.setCreateIp(createIp);
        rechargeLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
        this.rechargeLogRepository.save(rechargeLog);
        return rechargeLog;
    }

    /**
     * 用户充值成功
     * TODO 当前实现不支持手续费
     * @param id 充值记录编号
     * @param createIp IP地址
     */
    @Override
    public void rechargeSuccess(Integer id,String createIp) {
        RechargeLog rechargeLog = this.rechargeLogRepository.findOne(id);
        BigDecimal amount = rechargeLog.getMoney();
        rechargeLog.setResultMoney(amount);
        rechargeLog.setStatus(true);
        this.rechargeLogRepository.save(rechargeLog);
        logger.info("用户充值记录状态改变：完成充值");
        this.memberService.memberMoneyChange(rechargeLog.getMemberInfo(),amount, MemberMoneyLog.Type.RECHARGE,createIp);
    }

    @Override
    public void rechargeFail(Integer id,String createIp) {

    }


    @Override
    public Page<RechargeLog> findLoggerPage(String username,PageRequest pageRequest){
        MemberInfo memberInfo = this.memberInfoRepository.findByUsername(username);
        return this.rechargeLogRepository.findByMemberInfo(memberInfo,pageRequest);

    }
}
